define(['jquery', 'bootstrap', 'backend', 'table', 'form', '/assets/addons/kuerp/layui/layui.js'], function ($, undefined, Backend, Table, Form, Layui) {

    var Controller = {
        index: function () {

            layui.use(['table', 'form'], function () {
                var table = layui.table;

                var set = Config.set;
                var taxes = parseInt(set.taxes.is_checked);
                if (isNaN(taxes)) {
                    taxes = 0;
                }
                var taxesStatus = taxes !== 1;

                table.render({
                    elem: '#table',
                    url: 'kuerp/goods_sales_summaryc/index',
                    parseData: function (res) {
                        return {
                            "code": 0,
                            "msg": '',
                            "count": res.total,
                            "data": res.rows
                        };
                    },
                    toolbar: '#thisToolbar',
                    defaultToolbar: [
                        { name: 'filter', title: __('Filter') },
                        { name: 'exports', title: __('Exports') },
                        { name: 'print', title: __('Print') }
                    ],
                    page: true,
                    layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'],
                    page: {
                        prev: __('Previous'),
                        next: __('Next'),
                        first: __('First'),
                        last: __('Last'),
                        skipText: [__('Go to page'), '', __('Confirm')],
                        countText: [__('Total') + ' ', ' ' + __('Records')],
                        limitTemplet: function (item) {
                            return item + ' ' + __('Entries');
                        }
                    },
                    text: {
                        none: __('No data'),
                        loading: __('Loading...')
                    },
                    cellMinWidth: 80,
                    where: {
                        filter: JSON.stringify(getSearch()),
                        op: JSON.stringify(getOp())
                    },
                    cols: [[
                        { field: 'supplier_type_name', title: __('Supplier Type Name'), totalRowText: __('Total'), templet: function (d) {
                                return d.supplier_type_name || '';
                            } },
                        { field: 'supplyer_name', title: __('Customer ID'), templet: function (d) {
                                return d.supplyer_name || '';
                            } },
                        { field: 'goods_code', title: __('Goods Code'), width: 100 },
                        { field: 'goods_name', title: __('Goods Name') },
                        { field: 'goods_barcode', title: __('Goods Barcode'), width: 100 },
                        { field: 'goods_specification_id', title: __('Goods Specification ID') },
                        { field: 's_name', title: __('Store Name'), templet: function (d) {
                                return d.s_name || '';
                            } },
                        { field: 'unit_conversion', title: __('Unit Conversion'), templet: function (d) {
                                return d.unit_conversion || '';
                            } },
                        { field: 'basic_nmber', title: __('Secondary Unit Number'), templet: function (d) {
                                return d.unit_conversion ? d.basic_nmber : '';
                            } },
                        { field: 'u_name', title: __('Default Unit') },
                        { field: 'i_number', title: __('Basic Number') },
                        { field: 'unit_price', title: __('Unit Price') },
                        { field: 'tax_included', title: __('Tax Included Price'), templet: function (d) {
                                return d.tax_included;
                            }, hide: taxesStatus },
                        { field: 'all_money', title: __('Total Money') },
                        { field: 'tax_money', title: __('Tax Amount'), templet: function (d) {
                                return d.tax_money;
                            }, hide: taxesStatus },
                        { field: 'money_tax_price', title: __('Price Tax Total'), templet: function (d) {
                                return d.money_tax_price;
                            }, hide: taxesStatus }
                    ]],
                    done: function (res, curr, count) {
                        if (res.count === 0 && !searchStatus) {
                            var html = '<div class="layui-none no-results"><span>' + __('Please enter search criteria and click search') + '</span></div>';
                            $(".layui-table-main").html(html);
                        }
                    }
                });

                //头工具栏事件
                table.on('toolbar(table)', function (obj) {
                    switch (obj.event) {
                        case 'refresh':
                            table.reload('table', []);
                            break;
                    }
                });

                //搜索事件
                $('#search').on('click', function () {
                    table.reload('table', {
                        where: {
                            filter: JSON.stringify(getSearch()),
                            op: JSON.stringify(getOp()),
                        }
                        , page: {
                            curr: 1,
                            prev: __('Previous'),
                            next: __('Next'),
                            first: __('First'),
                            last: __('Last'),
                            skipText: [__('Go to page'), '', __('Confirm')],
                            countText: [__('Total') + ' ', ' ' + __('Records')],
                            limitTemplet: function (item) {
                                return item + ' ' + __('entries');
                            }
                        }
                    });
                });
                var searchStatus = false;
                function getSearch() {
                    var search = {};
                    var purchase_code = $('#purchase_code').val();
                    if (purchase_code != '') {
                        search.purchase_code = purchase_code;
                    }
                    var customers_id = $('#customers_id').val();
                    if (customers_id != '') {
                        search.customers_id = customers_id;
                    }
                    var sale_user = $('#sale_user').val();
                    if (sale_user != '') {
                        search.sale_user = sale_user;
                    }
                    var goods_code = $('#goods_code').val();
                    if (goods_code != '') {
                        search.goods_code = goods_code;
                    }
                    var purchase_time = $('#purchase_time').val();
                    if (purchase_time != '') {
                        search.purchase_time = purchase_time;
                    }
                    if (purchase_code == '' && customers_id == '' && sale_user == '' && goods_code == '' && purchase_time == '') {
                        searchStatus = false;
                        search.id = 1;
                    } else {
                        searchStatus = true;
                    }
                    return search;
                }
                function getOp() {
                    var op = {};
                    op.purchase_code = 'LIKE';
                    op.goods_code = '=';
                    op.purchase_time = 'RANGE';
                    return op;
                }
            });
            Controller.api.bindevent();
        },

        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                layui.use(['table', 'form'], function () {
                    //销售员
                    xmSelect.render({
                        el: '#sale_users',
                        filterable: true,
                        language: Config.lang == 'zh-cn' ? 'cn' : 'en',
                        tips: __('Please select salesperson'),
                        paging: true,
                        pageSize: 5,
                        pageRemote: true,
                        remoteMethod: function (val, cb, show, pageIndex) {
                            $.ajax({
                                url: "kuerp/staff_member/index",
                                type: 'GET',
                                crossOrigin: true,
                                dataType: 'json',
                                cache: false,
                                async: true,
                                data: {
                                    keywords: val,
                                    filter: JSON.stringify({ "name": val }),
                                    op: JSON.stringify({ "name": 'like' }),
                                    page: pageIndex,
                                    limit: 5
                                },
                                success: function (data) {
                                    var TotalCount = data.total;
                                    var Pages = Math.ceil(TotalCount / 5);
                                    var list = [];
                                    $(data.rows).each(function (k, v) {
                                        var row = [];
                                        row['name'] = v.name;
                                        row['value'] = v.id;
                                        list.push(row)
                                    });
                                    setTimeout(function () {
                                        cb(list, Pages)
                                    }, 100)
                                },
                                error: function (data) {
                                    cb([], 0);
                                }
                            });
                        },
                        on: function (data) {
                            var arr = data.arr;
                            var change = data.change;
                            var isAdd = data.isAdd;
                            if (!isAdd) {
                                $('#sale_user').val('');
                            }
                            if (change.length > 0) {
                                for (let i in arr) {
                                    if (change[0].parentId == arr[i].parentId) {
                                        arr.splice(i, 1, change[0]);
                                    }
                                }
                            }
                            if (arr.length > 0) {
                                if (arr[0]['value'] != undefined) {
                                    $('#sale_user').val(arr[0]['value']);
                                }
                            }
                            return Array.from(new Set(arr));
                        },
                    });
                    //商品
                    xmSelect.render({
                        el: '#goods_codes',
                        // filterable: true,
                        tips: __('Please select product'),
                        paging: true,
                        pageSize: 5,
                        pageRemote: true,
                        remoteMethod: function (val, cb, show, pageIndex) {
                            $.ajax({
                                url: "kuerp/goods/index",
                                type: 'GET',
                                crossOrigin: true,
                                dataType: 'json',
                                cache: false,
                                async: true,
                                data: {
                                    keywords: val,
                                    filter: JSON.stringify({ "goods_name": val }),
                                    op: JSON.stringify({ "goods_name": 'like' }),
                                    page: pageIndex,
                                    limit: 5
                                },
                                success: function (data) {
                                    var TotalCount = data.total;
                                    var Pages = Math.ceil(TotalCount / 5);
                                    var list = [];
                                    $(data.rows).each(function (k, v) {
                                        var row = [];
                                        row['name'] = v.goods_name;
                                        row['value'] = v.goods_code;
                                        list.push(row)
                                    });
                                    setTimeout(function () {
                                        cb(list, Pages)
                                    }, 100)
                                },
                                error: function (data) {
                                    cb([], 0);
                                }
                            });
                        },
                        on: function (data) {
                            var arr = data.arr;
                            var change = data.change;
                            var isAdd = data.isAdd;
                            if (!isAdd) {
                                $('#goods_code').val('');
                            }
                            if (change.length > 0) {
                                for (let i in arr) {
                                    if (change[0].parentId == arr[i].parentId) {
                                        arr.splice(i, 1, change[0]);
                                    }
                                }
                            }
                            if (arr.length > 0) {
                                if (arr[0]['value'] != undefined) {
                                    $('#goods_code').val(arr[0]['value']);
                                }
                            }
                            return Array.from(new Set(arr));
                        },
                    });
                });
                layui.use(['table', 'form'], function () {
                    var supplyer_div = xmSelect.render({
                        el: '#customers_ids',
                        // filterable: true,
                        paging: true,
                        tips: __('Please select customer'),
                        language: Config.lang == 'zh-cn' ? 'cn' : 'en',
                        pageSize: 5,
                        // remoteSearch: true,
                        pageRemote: true,
                        remoteMethod: function (val, cb, show, pageIndex) {
                            $.ajax({
                                url: "kuerp/customers/index",
                                type: 'GET',
                                crossOrigin: true,
                                dataType: 'json',
                                cache: false,
                                async: true,
                                data: {
                                    keywords: val,
                                    filter: JSON.stringify({ "customer_name": val }),
                                    op: JSON.stringify({ "customer_name": 'like' }),
                                    page: pageIndex,
                                    limit: 5
                                },
                                success: function (data) {
                                    var TotalCount = data.total;
                                    var Pages = Math.ceil(TotalCount / 5);
                                    var list = [];
                                    $(data.rows).each(function (k, v) {
                                        var row = [];
                                        row['name'] = v.customer_name;
                                        row['value'] = v.id;
                                        list.push(row)
                                    });
                                    setTimeout(function () {
                                        cb(list, Pages)
                                    }, 100)
                                },
                                error: function (data) {
                                    cb([], 0);
                                }
                            });
                        },
                        on: function (data) {
                            var arr = data.arr;
                            var change = data.change;
                            var isAdd = data.isAdd;
                            if (!isAdd) {
                                $('#customers_id').val('');
                            }
                            if (change.length > 0) {
                                for (let i in arr) {
                                    if (change[0].parentId == arr[i].parentId) {
                                        arr.splice(i, 1, change[0]);
                                    }
                                }
                            }
                            if (arr.length > 0) {
                                if (arr[0]['value'] != undefined) {
                                    $('#customers_id').val(arr[0]['value']);
                                }
                            }
                            return Array.from(new Set(arr));
                        },
                    });

                    var kuerp_customers = Config.kuerp_customers;
                    if (kuerp_customers != undefined) {
                        var newArr = [];
                        newArr.push({ name: kuerp_customers.customer_name, value: kuerp_customers.id, });
                        supplyer_div.setValue(newArr);
                    }

                    var set = Config.set;
                    var examine = parseInt(set.examine.is_checked);
                    if (isNaN(examine)) {
                        examine = 0;
                    }
                    if (examine == 1 && Config.examine_status == 1) {
                        supplyer_div.update({ disabled: true })
                    }
                });
                layui.use('laydate', function () {
                    var laydate = layui.laydate;
                    laydate.render({
                         lang: Config.lang == 'zh-cn' ? 'cn' : 'en',
                        elem: '#purchase_time',
                        type: 'datetime',
                        range: true
                    });
                });
                Form.api.bindevent($("form[role=form]"), function (data, ret) {
                    parent.location.reload();
                });
            }
        }
    };
    return Controller;
});